package cn.iocoder.yudao.module.policy.controller.utils;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DoubaoAIUtils {

    // 默认API地址（可在构造方法中覆盖）
    private static final String DEFAULT_API_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
    private  String apiUrl;
    private String apiKey="0aa6d698-676d-48bd-982c-58b140992bfb";
    private  ObjectMapper objectMapper;

    static final String key = "0aa6d698-676d-48bd-982c-58b140992bfb";
    static final String modelId = "ep-20250524234845-b5hvt";
    static final String url = "rpi-20250524221215-l6ftp";
    static final String content_type = "application/json; charset=utf-8";

    /**
     * 同步调用豆包AI
     *
     * @param request 请求参数
     * @return 豆包响应内容
     * @throws DoubaoAIException 调用异常
     */
    public DoubaoResponse call(DoubaoRequest request) throws DoubaoAIException {
        try {
            // 1. 参数校验
            validateRequest(request);

            // 2. 构建HTTP请求
            HttpURLConnection connection = buildConnection();
            sendRequest(connection, request);

            // 3. 处理响应
            return handleResponse(connection);
        } catch (Exception e) {
            throw new DoubaoAIException("调用豆包API失败: " + e.getMessage(), e);
        }
    }

    /**
     * 快速调用（简化版）
     *
     * @param userMessage 用户消息
     * @return AI回复内容（直接返回字符串）
     */
    public String quickCall(String userMessage) throws DoubaoAIException {
        DoubaoRequest request = new DoubaoRequest();
        request.setModel("ep-20250524234845-b5hvt");
        request.addMessage("system", "You are a helpful assistant.");
        request.addMessage("user", userMessage);

        DoubaoResponse response = call(request);
        return response.getChoices().get(0).getMessage().getContent();
    }

    // ---------- 私有方法 ----------
    private void validateRequest(DoubaoRequest request) {
        if (request == null) {
            throw new IllegalArgumentException("请求参数不能为空");
        }
        if (StrUtil.isEmpty(request.getModel())) {
            throw new IllegalArgumentException("model参数不能为空");
        }
        if (request.getMessages() == null || request.getMessages().isEmpty()) {
            throw new IllegalArgumentException("messages参数不能为空");
        }
    }

    private HttpURLConnection buildConnection() throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(apiUrl).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setConnectTimeout(5000);  // 5秒连接超时
        connection.setReadTimeout(30000);   // 30秒读取超时
        connection.setDoOutput(true);
        return connection;
    }

    private void sendRequest(HttpURLConnection connection, DoubaoRequest request) throws IOException {
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = objectMapper.writeValueAsString(request).getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }
    }

    private DoubaoResponse handleResponse(HttpURLConnection connection) throws IOException {
        int statusCode = connection.getResponseCode();
        if (statusCode != HttpURLConnection.HTTP_OK) {
            String errorMsg = readErrorResponse(connection);
            throw new IOException("HTTP错误码: " + statusCode + ", 错误信息: " + errorMsg);
        }

        try (InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            return objectMapper.readValue(br, DoubaoResponse.class);
        }
    }

    private String readErrorResponse(HttpURLConnection connection) {
        try (InputStream es = connection.getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(es, StandardCharsets.UTF_8))) {
            StringBuilder errorResponse = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                errorResponse.append(line);
            }
            return errorResponse.toString();
        } catch (Exception e) {
            return "无法读取错误响应";
        }
    }


    // ---------- DTO定义 ----------
    @Data
    public static class DoubaoRequest {
        private String model;
        private List<Message> messages = new ArrayList<>();

        public void addMessage(String role, String content) {
            this.messages.add(new Message(role, content));
        }
    }

    @Data
    public static class DoubaoResponse {
        private List<Choice> choices;
        // 其他可能的响应字段...
    }

    @Data
    public static class Message {
        private String role;
        private String content;

        public Message(String role, String content) {
            this.role = role;
            this.content = content;
        }
    }

    @Data
    public static class Choice {
        private Message message;
        // 其他可能的choice字段...
    }

    // ---------- 自定义异常 ----------
    public static class DoubaoAIException extends Exception {
        public DoubaoAIException(String message) {
            super(message);
        }

        public DoubaoAIException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}
